import { asyncRoutes, constantRoutes } from '@/router'
import { menulist } from '@/api/user'

import XEUtils from 'xe-utils'
import Layout from '@/layout'


/**
 * 导入路由组件 - webpack4支持
 * @param view
 * @returns {function(*=): any}
 * @private
 */
function _import (view) {
  return (resolve) => require([`@/views/${view}`], resolve)
}

/**
 * 导入路由组件
 * @param view
 * @returns {function(): Promise<*>}
 */
const loadView = (view) => {
  return () => import(`@/views/${view}`)
};

/**
 * 获取登录后的动态路由
 * @param roles
 */
async function getAsyncRoutesByApi(resourceNameList) {

  let asyncRoutesArr = [],asyncRoutesArrMap = [],dataRowsMap = []
  // let funccodeNameStr
  return await menulist({
    // funccodeName:resourceNameList.join(" ")
    funccodeName:resourceNameList
  }).then(({data}) => {
    console.log('YYYYYYYYYYYYYYYYYY',data);
    dataRowsMap =  XEUtils.map(XEUtils.clone(data.rows, true), item => {
      return {
        ...item,
        parent_code:parseInt(item.parent_code),
        p_code:parseInt(item.p_code)
      }
    })
    console.log('dataRowsMapdataRowsMapdataRowsMap',dataRowsMap)

    // 数组改为路由树节点
    asyncRoutesArr = XEUtils.toArrayTree(XEUtils.clone(dataRowsMap, true), {
      strict: true, 
      parentKey: 'parent_code', 
      key: 'p_code', 
    })
    console.log('asyncRoutesArr',asyncRoutesArr);
    // 重置路由树节点数据
    asyncRoutesArrMap = XEUtils.mapTree(XEUtils.clone(asyncRoutesArr, true), item => {
      let component 
      if (!item.component.startsWith("Layout")) {
        component =  loadView(item.component)
      }else{
        component = Layout
      }
      return {
        path: item.path,
        component: component,
        redirect: (item.redirect === 'noRedirect')?'':item.redirect,
        name: item.name,
        hidden: item.hiden === 'true',
        // alwaysShow: (item.always_show === 'true')? true: false,
        meta: {
          title: item.meta_title.toString(),
          icon: item.meta_icon,
          noCache: item.meta_no_cache === 'true',
          affix: item.meta_affix === 'true',
          // breadcrumb: (item.meta_breadcrumb === 'true')? true: false,
        }
      }
    })

    console.log('asyncRoutesArrMapasyncRoutesArrMapasyncRoutesArrMap',asyncRoutesArrMap);
    console.log('asyncRoutesasyncRoutesasyncRoutes',asyncRoutes);
    return asyncRoutesArrMap

  })

}


/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    console.log('constantRoutes::::::::::',constantRoutes);
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, resourceNameList) {
    return new Promise(resolve => {


      
      // console.log('xxxdd',resourceNameList);
      

      let roles = ['admin']
      let accessedRoutes
      // 是否是用路由文件渲染路由
      if (process.env.VUE_APP_IS_ASYNCROUTES_FILE == 'YES') {
        if (roles.includes('admin')) {
          console.log('因为是超级管理员所有权限全开');
          accessedRoutes = asyncRoutes || []
        } else {
          accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
        }
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      }else{
        getAsyncRoutesByApi(resourceNameList).then((asyncRoutesArrMap) => {
          console.log('asyncRoutesasyncRoutesasyncRoutesasyncRoutesasyncRoutes',asyncRoutesArrMap);
          commit('SET_ROUTES', asyncRoutesArrMap)
          resolve(asyncRoutesArrMap)
        })
      }
      

      // 判断是否启用后端获取路由列表做权限控制
      // if (true) {
      //   if (roles.includes('admin')) {
      //     console.log('因为是超级管理员所有权限全开');
      //     // accessedRoutes = asyncRoutes || []
      //     accessedRoutes = getAsyncRoutesByApi().then((asyncRoutesArrMap) => {
      //       console.log('asyncRoutesasyncRoutesasyncRoutesasyncRoutesasyncRoutes',asyncRoutesArrMap);
      //       commit('SET_ROUTES', asyncRoutesArrMap)
      //       resolve(asyncRoutesArrMap)
      //     })
      //     // accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      //   } else {
      //     accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      //   }
      // }else{

      //   if (roles.includes('admin')) {
      //     console.log('因为是超级管理员所有权限全开');
      //     accessedRoutes = asyncRoutes || []
      //     // accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      //   } else {
      //     accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      //   }
      //   commit('SET_ROUTES', accessedRoutes)
      //   resolve(accessedRoutes)

      // }

    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
